package cn.wolfcode.luowowo.comment.service.impl;


import cn.wolfcode.luowowo.comment.domain.ProblemComment;
import cn.wolfcode.luowowo.comment.query.ProblemCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ProblemCommentRepository;
import cn.wolfcode.luowowo.comment.service.IProblemCommentService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class ProblemCommentServiceImpl implements IProblemCommentService {
    @Autowired
    private ProblemCommentRepository repository;
    @Autowired
    private MongoTemplate mongoTemplate;

    public ProblemComment save(ProblemComment comment) {


        comment.setCreateTime(new Date());
        //需要额外处理评论的评论
        if(comment.getType() == ProblemComment.PROBLEM_COMMENT_TYPE){
            String refId = comment.getRefComment().getId();
            if(StringUtils.hasLength(refId)){
                ProblemComment problemComment = repository.findById(refId).get();
                comment.setRefComment(problemComment);
            }
        }




        repository.save(comment);
        return comment;
    }

    public Page query(ProblemCommentQuery qo) {
        Query query = new Query();
        //Criteria criteria = new Criteria("detailId").is(qo.getDetailId());
        //Criteria.where("detailId") =new Criteria(detailId)
        //注意这里的page当前页是从0开始的
        Pageable pageable= PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"createTime");
        //查询总条数
        long count = mongoTemplate.count(query, ProblemComment.class);
        query.with(pageable);
        //查询当前显示数据集合
        if(qo.getProblemId()!=-1){
            query.addCriteria(Criteria.where("problemId").is(qo.getProblemId()));
        }
        List<ProblemComment> problemComments = mongoTemplate.find(query, ProblemComment.class);

        return new PageImpl(problemComments,pageable,count);
    }

    @Override
    public long getCount(Long problemId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("problemId").is(problemId));
        long count = mongoTemplate.count(query, ProblemComment.class);
        return count;
    }

}
